package com.chuangshi.core.vote.member.controller.mobile;

import cn.hutool.core.util.StrUtil;
import com.chuangshi.core.exception.BusinessException;
import com.chuangshi.core.kit.Controller;
import com.chuangshi.core.kit.IdWorker;
import com.chuangshi.core.token.TokenService;
import com.chuangshi.core.vote.member.controller.admin.request.MemberAdminV1UpdateRequest;
import com.chuangshi.core.vote.member.controller.mobile.request.*;
import com.chuangshi.core.vote.member.controller.mobile.response.*;
import com.chuangshi.core.vote.member.entity.Member;
import com.chuangshi.core.vote.member.service.MemberService;
import io.swagger.annotations.*;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 会员移动端控制器
 *
 * @author marcus
 * @date 2018-11-20
 */
@Api(tags = "会员移动端控制器")
@RestController
public class MemberMobileController extends Controller {

    public static final Logger log = LoggerFactory.getLogger(MemberMobileController.class);

    @Autowired
    private MemberService memberService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WxMpService wxMpService;

    @Value("${weixin.open.website.appId}")
    private String weixinOpenWebsiteAppId;

    @Value("${weixin.open.website.appSecret}")
    private String weixinOpenWebsiteAppSecret;

    @Value("${weixin.open.website.redirectURI}")
    private String redirectURI;

//    @ApiOperation(value = "微信授权登陆", httpMethod = "GET")
//    @RequestMapping(value = "/vote/member/open/v1/wechat/open/auth", method = RequestMethod.GET)
//    public void v1WechatOpenAuth(
//            @ApiParam(name = "回调url") @RequestParam("state") String state,
//            HttpServletResponse response) throws Exception {
//
//        WxMpInMemoryConfigStorage wxConfigProvider = new WxMpInMemoryConfigStorage();
//        wxConfigProvider.setAppId(weixinOpenWebsiteAppId);
//        wxConfigProvider.setSecret(weixinOpenWebsiteAppSecret);
//        wxMpService.setWxMpConfigStorage(wxConfigProvider);
//
//        String redirect = wxMpService.oauth2buildAuthorizationUrl(redirectURI, WxConsts.OAuth2Scope.SNSAPI_BASE, URLEncoder.encode(state, "UTF-8"));
//
//        response.sendRedirect(redirect.replace("redirect:", ""));
//    }

    @ApiOperationSort(value = 10)
    @ApiOperation(value = "微信登陆", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "body", value = "请求参数", required = true, paramType = "body", dataType = "MemberMobileV1LoginBySmsRequest")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "登陆成功", response = MemberMobileV1MobileLoginResponse.class)
    })
    @RequestMapping(value = "/vote/member/open/v1/wechat/open/login", method = {RequestMethod.POST}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> v1Login(@ApiIgnore @RequestBody MemberMobileV1LoginBySmsRequest body) {

        WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage = new WxMpInMemoryConfigStorage();
        wxMpInMemoryConfigStorage.setAppId(weixinOpenWebsiteAppId);
        wxMpInMemoryConfigStorage.setSecret(weixinOpenWebsiteAppSecret);

        wxMpService.setWxMpConfigStorage(wxMpInMemoryConfigStorage);

        WxMpOAuth2AccessToken accessToken = null;
        try {
            accessToken = wxMpService.oauth2getAccessToken(body.getCode());
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new BusinessException("登陆失败");
        }

        if (accessToken == null || StrUtil.isEmpty(accessToken.getOpenId())) {
            throw new BusinessException("授权失败");
        }
        Member member = memberService.findByOpenId(accessToken.getOpenId());
        if (member == null) {
            member = new Member();
            member.setMemberId(IdWorker.getIdStr());
            member.setUserId(IdWorker.getIdStr());
            member.setAppId(body.getAppId());
            member.setMemberWechatMpOpenId(accessToken.getOpenId());
            member.setMemberWechatUnionId(accessToken.getUnionId() != null ? accessToken.getUnionId() : "");
            memberService.save(member);
        }
        String token = tokenService.encode(member.getUserId(), member.getMemberId(), member.getAppId());

        MemberMobileV1MobileLoginResponse response = new MemberMobileV1MobileLoginResponse();
        response.setToken(token);
        response.setWechatOpenId(accessToken.getOpenId());
        validateResponse(MemberMobileV1MobileLoginResponse.class);
        return renderJson(response);
    }

    @ApiOperationSort(value = 40)
    @ApiOperation(value = "获取单条会员", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "body", value = "请求参数", required = true, paramType = "body", dataType = "MemberMobileV1FindRequest")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "返回参数", response = MemberMobileV1FindResponse.class)
    })
    @RequestMapping(value = "/vote/member/mobile/v1/find", method = {RequestMethod.POST}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> v1Find(@ApiIgnore @RequestBody MemberMobileV1FindRequest body) {
        validateRequest(body);

        Member member = memberService.find(body.getObjectId());

        validateResponse(MemberMobileV1FindResponse.class);

        return renderJson(member);
    }

}